package com.foreknow.controller;

import com.foreknow.model.Guestbook;
import com.foreknow.service.impl.GuestbookServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * web资源跳转
 * 两种方式:
 * 1.请求转发(站内跳转)
 * 2.重定向(站外跳转)
 */
public class AddMessageServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {


    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//        resp.setContentType("text/html;charset = utf-8");
//        //客户端向服务器端请求内容的字符编码集
//        req.setCharacterEncoding("utf-8");
        PrintWriter out = resp.getWriter();
       //获取到请求的参数
       String name =  req.getParameter("name");
       String phone = req.getParameter("phone");
       String email = req.getParameter("email");
       String title= req.getParameter("title");
       String content = req.getParameter("content");

       //调用service方法 save
        GuestbookServiceImpl service = new GuestbookServiceImpl();
        Guestbook gb = new Guestbook();
        gb.setName(name);
        gb.setPhone(phone);
        gb.setEmail(email);
        gb.setTitle(title);
        gb.setContent(content);
        SimpleDateFormat sdf =  new SimpleDateFormat("yyyy-MM-dd");
        gb.setCreatedtime(sdf.format(new Date()));
        boolean isOK = service.save(gb);
        if(isOK){
            //out.println("<a href='/WebDemoMVC/user/get'> 查看所有的留言信息</a>");
//            请求转发
            req.getRequestDispatcher("/user/get").forward(req,resp);
            //重定向
            //resp.sendRedirect(req.getContextPath()+"/user/get");

        }else{
            out.println("添加失败");
        }
    }
}






